import schedule from 'node-schedule'
import User from '../service/User'
import { GET, POST } from '../common/Request'
import CONFIG from '../config'

export default {
    start : () =>{
        let rule2     = new schedule.RecurrenceRule();
        let times2    = [1,6,11,16,21,26,31,36,41,46,51,56];
        rule2.second  = times2;
        //rule2.minute  = times2;
        schedule.scheduleJob(rule2, async() => {
            let data = await GET(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${CONFIG.APPID}&secret=${CONFIG.SECRET}`)
            if(data.errcode){
                throw { errMsg : '无法获取APP Token' }
            }
            let users = await User.findNoBuys()
            for (const index in users) {
                let u = users[index]
                if(u.formId){
                    let res = await POST(`https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${data.access_token}`, {
                        template_id : CONFIG.message_no_pay,
                        page : 'pages/home/pay',
                        touser : u.id,
                        form_id : u.formId,
                        data : {
                            "keyword1" : { value : '绑定成功'},
                            "keyword2" : { value : u.phone},
                            "keyword3" : { value : u.province + u.carnumber},
                            "keyword4" : { value : '您还未购买挪车号码隐藏服务,点击进行购买!'},
                        }
                    })
                    u.send = 1
                    u.save()
                }
            }
        })
    }
}